<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="ruleForm"
				:model="queryData"
				label-width="100px"
				label-suffix=":"
				:inline="true"
			>
				<el-form-item :label="`商品类型`">
					<el-select
						v-model="queryData.goodsTypeList"
						clearable
						:placeholder="`${$t('common.select_all')}`"
						style="width:220px"
						multiple
					>
						<el-option
							v-for="item in productTypeArr"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="`商品名称`">
					<el-input
						v-model.trim="queryData.goodsName"
						v-input="{ name: 'symbols' }"
						clearable
						:placeholder="`${$t('common.please_enter')}`"
					></el-input>
				</el-form-item>
				<el-form-item :label="`商品状态`">
					<el-select
						v-model="queryData.status"
						clearable
						:placeholder="`${$t('common.select_all')}`"
						style="width:220px"
					>
						<el-option
							v-for="item in productStatusArr"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						:disabled="loading"
						:loading="loading"
						size="medium"
						@click="handleSearch"
					>
						{{ $t('dxn.card_ables_list.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-right"
						size="medium"
						@click="reset"
					>
						{{ $t('dxn.card_ables_list.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('90870108')"
						type="warning"
						icon="el-icon-download"
						size="medium"
						:loading="exportBtnLoading"
						@click="exportExcel"
					>
						{{ $t('dxn.card_ables_list.export_excel') }}
					</el-button>
				</el-form-item>
			</el-form>
		</template>
		<template slot="content">
			<el-table
				ref="refTable"
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				size="mini"
				class="small-size-table"
				border
				:data="list"
				style="width: 100%"
				:max-height="tableHeight"
				:header-cell-style="getRowClass"
				highlight-current-row
				header-align="center"
			>
				<el-table-column
					type="index"
					label="序号"
					width="80"
					align="center"
				/>
				<el-table-column
					:label="`商品类型`"
					min-width="120"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.goodsTypeName || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					label="商品编号"
					min-width="130"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.goodsCode || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					:label="`商品名称`"
					:min-width="columnWidth.goodsName"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<el-input
							v-if="isEditSelectRow(scope.$index)"
							id="submitFormGoodsName"
							v-model="submitForm.goodsName"
							style="width: 240px;"
							:maxlength="20"
							v-input="{ name: 'symbols' }"
							@blur="handleBlurCheckGoodsName(scope.row)"
						/>
						<span v-else>
							{{ scope.row.goodsName || '-' }}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					:label="`商品状态`"
					:min-width="columnWidth.status"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<el-select
							v-if="isEditSelectRow(scope.$index)"
							v-model="submitForm.status"
							style="width:90px"
						>
							<el-option
								v-for="item in productStatusArr"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
						<span v-else>
							{{ scope.row.statusName || '' }}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					:label="`商品描述`"
					:min-width="columnWidth.describe"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<el-input
							v-if="isEditSelectRow(scope.$index)"
							v-model="submitForm.describe"
							style="width: 240px;"
							:maxlength="200"
							v-input="{ name: 'noEmpty' }"
						/>
						<span v-else>
							{{ scope.row.describe || '-' }}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					label="资源编号"
					min-width="130"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.resourceCode || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					label="创建时间"
					min-width="160"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.createdAt || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					:label="`创建人`"
					min-width="120"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.createdBy || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					label="最后操作时间"
					min-width="160"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.updatedAt || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					:label="`最后操作人`"
					min-width="120"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.updatedBy || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					:label="`${$t('dxn.card_ables_list.operate')}`"
					min-width="180"
					align="center"
					fixed="right"
				>
					<template slot-scope="scope">
						<template v-if="isEditSelectRow(scope.$index)">
							<el-button
								type="text"
								class="action-button"
								:disabled="submitLoading"
								@click="handleCancel"
							>
								{{ $t('common.cancel') }}
							</el-button>
							<el-button
								type="text"
								class="action-button"
								:loading="submitLoading"
								@click="handleSubmit"
							>
								{{ $t('common.save') }}
							</el-button>
						</template>
						<template v-else>
							<template v-if="hasPermission('90870110')">
								<el-button
									v-if="scope.row.status === 2"
									type="text"
									class="action-button"
									:disabled="isEdit"
									:loading="
										submitLoading &&
											currentIndex === scope.$index
									"
									@click="handleOpenClose(1, scope.row.id)"
								>
									禁用
								</el-button>
								<el-button
									v-else
									type="text"
									class="action-button"
									:disabled="isEdit"
									:loading="
										submitLoading &&
											currentIndex === scope.$index
									"
									@click="handleOpenClose(2, scope.row.id)"
								>
									开启
								</el-button>
							</template>
							<el-button
								v-if="hasPermission('90870109')"
								type="text"
								class="action-button"
								:disabled="isEdit"
								@click="handleEdit(scope)"
							>
								编辑
							</el-button>
						</template>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-show="!!total"
				class="pageValue"
				:current-page.sync="pageNum"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size="pageSize"
				:page-sizes="$store.getters.pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
	</main-content>
</template>

<script>
import { routerNames } from '@/utils/consts'
import list from '@/mixins/list'
import MainContent from '@/components/MainContent/index.vue'
import { productStatusArr } from '@/views/dxn/shopManager/components/constants'

export default {
	name: routerNames.productBasicConfig,
	components: {
		MainContent
	},
	mixins: [list],
	data() {
		return {
			loading: false,
			list: [],
			exportBtnLoading: false,
			tableHeight: 480,
			otherDependenComponents: [],
			queryData: {
				status: '',
				goodsName: '',
				goodsTypeList: []
			},
			isEdit: false,
			isCheckRepeat: true,
			submitLoading: false,
			submitForm: {},
			submitGoodsCode: undefined,
			currentIndex: undefined,
			productStatusArr,
			productTypeArr: []
		}
	},
	computed: {
		columnWidth() {
			if (this.isEdit) {
				return {
					goodsName: 270,
					status: 135,
					describe: 270
				}
			} else {
				return {
					goodsName: 150,
					status: 100,
					describe: 160
				}
			}
		}
	},
	watch: {
		$route: function(to, from) {
			if (to.path.indexOf(routerNames.productBasicConfig) > -1) {
				this.getRouteQuery(true)
			}
		}
	},
	created() {
		this.getRouteQuery()
		this.getProductTypeArr()
	},
	methods: {
		// 获取商品类型配置
		getProductTypeArr() {
			this.productTypeArr = []
			this.$api
				.getBackendEnumListBend({ code: 1001 })
				.then((res) => {
					this.productTypeArr = res?.data || []
				})
				.catch(() => {})
		},
		// 商品名称重复检查
		async handleBlurCheckGoodsName(row) {
			// 避免失焦获取焦点来回切换
			if (!this.isCheckRepeat) {
				return false
			}
			const params = {
				goodsCode: this.submitGoodsCode,
				goodsName: this.submitForm.goodsName
			}
			if (this.isEmptyOrNullOrUndefined(params.goodsName)) {
				return false
			}
			try {
				const res = await this.$api.getMallProductIfExistBend(params)
				if (res?.data?.id !== undefined) {
					this.$message.closeAll()
					this.$message.warning('商品名称重复')
					document.getElementById('submitFormGoodsName').focus()
					return true
				}
			} catch (err) {
				return false
			}
			return false
		},
		// 请求
		getRouteQuery(isLoadData = false) {
			if (this.$route.query.goodsName) {
				this.queryData.status = ''
				this.queryData.goodsTypeList = []
				this.queryData.goodsName = this.$route.query.goodsName || ''
				this.$router.replace({ query: {} })
				if (isLoadData) {
					this.loadData()
				}
			}
		},
		handleEdit(scope) {
			this.currentIndex = scope.$index
			this.isEdit = true
			this.submitForm = {
				id: scope.row.id,
				goodsName: scope.row.goodsName,
				describe: scope.row.describe,
				status: scope.row.status
			}
			this.submitGoodsCode = scope.row.goodsCode
		},
		async handleSubmit() {
			const params = { ...this.submitForm }
			if (this.isEmptyOrNullOrUndefined(params.goodsName)) {
				this.$message.closeAll()
				this.$message.warning('商品名称未配置，请检查')
				return
			}
			this.submitLoading = true
			this.$api
				.updateMallProducBend(params)
				.then((res) => {
					this.submitLoading = false
					if (res?.code === 200) {
						this.$message.success('保存成功')
						this.resetSubmitForm()
						this.loadData()
					}
				})
				.catch(() => {
					this.submitLoading = false
				})
				.finally(() => {})
		},
		handleCancel() {
			this.isCheckRepeat = false
			this.$confirm(
				'是否取消本次编辑操作？',
				this.$t('common.components.tip'),
				{
					confirmButtonText: this.$t('common.sure'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning'
				}
			)
				.then(() => {
					this.resetSubmitForm()
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					})
				})
				.finally(() => {
					this.isCheckRepeat = true
				})
		},
		resetSubmitForm() {
			this.currentIndex = undefined
			this.submitForm = {}
			this.isEdit = false
		},
		isEmptyOrNullOrUndefined(val) {
			return val === '' || val === null || val === undefined
		},
		isEditSelectRow(index) {
			return this.isEdit && this.currentIndex === index
		},
		// 1禁用 2开启
		handleOpenClose(val, id) {
			this.$confirm(
				`${
					val === 2
						? '是否对该商品进行开启操作？'
						: '是否对该商品进行禁用操作？'
				}`,
				this.$t('common.components.tip'),
				{
					confirmButtonText: this.$t('common.sure'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning'
				}
			)
				.then(() => {
					this.submitLoading = true
					const params = {
						id: id,
						status: val
					}
					this.$api
						.updateMallProducBend(params)
						.then((res) => {
							this.submitLoading = false
							if (res?.code === 200) {
								this.$message.success(
									val === 2 ? '开启成功' : '禁用成功'
								)
								this.loadData()
							}
						})
						.catch(() => {
							this.submitLoading = false
						})
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					})
				})
		},
		getCurrentParams() {
			const params = {
				...this.queryData
			}
			if (!params.goodsTypeList?.length) {
				params.goodsTypeList = undefined
			}
			return params
		},
		loadData() {
			const params = this.getParams(this.getCurrentParams())
			this.loading = true
			this.list = []
			this.$api
				.getMallProductListBend(params)
				.then((res) => {
					this.loading = false
					const { record = [], totalRecord } = res.data || {}
					this.list = record
					this.total = totalRecord || 0
				})
				.catch(() => {
					this.loading = false
				})
		},
		handleSearch() {
			this.resetSubmitForm()
			this.pageNum = 1
			this.loadData()
		},
		reset() {
			this.resetSubmitForm()
			Object.keys(this.queryData).forEach((key) => {
				if (Array.isArray(this.queryData[key])) {
					this.queryData[key] = []
				} else {
					this.queryData[key] = undefined
				}
			})
			this.pageNum = 1
			this.loadData()
		},
		exportExcel() {
			const params = this.getParams(this.getCurrentParams())
			params.pageSize = undefined
			params.pageNum = undefined
			this.exportBtnLoading = true
			this.exportExcelPublic({
				api: 'exportMallProductListBend',
				params
			}).finally(() => {
				this.exportBtnLoading = false
			})
		},
		// 跳转
		handleJump(obj) {
			this.$router.push(obj)
		}
	}
}
</script>
<style lang="scss" scoped>
.text-click {
	color: #409eff;
	cursor: pointer;
}
.action-button {
	min-width: 30px !important;
}
</style>
